package com.cxyhome.controller;

import com.cxyhome.mapper.MenuMapper;
import com.cxyhome.pojo.Menu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.PostConstruct;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by wudi on 2016/9/16.
 */
@Controller
@RequestMapping("/")
public class IndexController {


    private static final Logger logger = LoggerFactory
            .getLogger(IndexController.class);

    @PostConstruct
    public void logSomething() {
        logger.debug("Sample Debug Message");
        logger.trace("Sample Trace Message");
    }

    @Autowired
    private MenuMapper menuMapper;


    @GetMapping
    public ModelAndView list() {
        logger.debug("all");
        List<Menu> menus = this.menuMapper.findAll();
        return new ModelAndView("menu/list", "menus", menus);
    }


    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id) {
        Menu menu = this.menuMapper.findMenu(id);
        return new ModelAndView("menu/view", "menu", menu);
    }

    @GetMapping(params = "form")
    public String createForm(@ModelAttribute Menu menu) {
        return "menu/form";
    }

    @PostMapping
    public ModelAndView create(@Valid Menu menu, BindingResult result,
                               RedirectAttributes redirect) {
        if (result.hasErrors()) {
            return new ModelAndView("menu/form", "formErrors", result.getAllErrors());
        }
        long result1= 0L;
        if (menu.getMenuid() == null) {
            result1=       this.menuMapper.save(menu);
        } else {
            result1=   this.menuMapper.update(menu);
        }
        redirect.addFlashAttribute("globalmenu", "Successfully created a new menu");
        return new ModelAndView("redirect:/{menu.id}", "menu.id", menu.getMenuid());
    }

    @RequestMapping("foo")
    public String foo() {
        throw new RuntimeException("Expected exception in controller");
    }

    @GetMapping(value = "delete/{id}")
//	@DeleteMapping(value = "delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id) {
        this.menuMapper.deleteMenu(id);
        List<Menu> menus = this.menuMapper.findAll();
        return new ModelAndView("menu/list", "menus", menus);
    }

    @GetMapping(value = "modify/{id}")
    public ModelAndView modifyForm(@PathVariable("id") Long id) {
//        menu = this.menuMapper.save(menu);
        Menu menu = this.menuMapper.findMenu(id);
        return new ModelAndView("menu/form", "menu", menu);
    }

}
